<?php 
/**
 * Created by Sublime
 * User: yinni
 * Date: 2017/10/01
 * Time: 21:25
 */
namespace App\Services\Admin;

use Facades\App\Repositories\Eloquent\CoringRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Monitor_alarmRepositoryEloquent;
use Facades\App\Repositories\Eloquent\MonitorRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Monitor_alarm_historyRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Room_loopRepositoryEloquent;
use Facades\App\Repositories\Eloquent\UserRepositoryEloquent;
use Facades\Yajra\Datatables\Html\Builder;
use App\Traits\DatatableActionButtonTrait;
use Datatables;
use Exception;
use DB;

class AlarmService{
	use DatatableActionButtonTrait;

	protected $module = 'alarm'; //模块路由

	protected $indexRoute = 'alarm.index'; 

	protected $createRoute = 'alarm.create';

	protected $showRoute = 'alarm.show';

	protected $editRoute = 'alarm.edit';

	protected $destroyRoute = 'alarm.destroy';
    public function __construct() {
        // 定义当前需使用的数据表
        $this->coring = CoringRepositoryEloquent::all();
        $this->monitor = MonitorRepositoryEloquent::all();
        $this->monitor_alarm = Monitor_alarmRepositoryEloquent::all();
        $this->monitor_alarm_history = Monitor_alarm_historyRepositoryEloquent::all();
        $this->room_loop = Room_loopRepositoryEloquent::all();        
    }
	/**
	 * 首页
	 * @return array
	 */
	public function index() {
		if(request()->ajax()) {
			return $this->ajaxData();
		}
        $html = Builder::parameters([
            'searchDelay' => 350,
            'language' => [
                'url' => url(getThemeAssets('dataTables/language/zh.json', true))
            ],
            'drawCallback' => <<<Eof
					function() {
				        LaravelDataTables["dataTableBuilder"].$('.tooltips').tooltip( {
				          placement : 'top',
				          html : true
				        });
			        },
Eof
        ])->addIndex(['data' => 'DT_Row_Index', 'name' => 'DT_Row_Index', 'title' => trans('common.number')])
            ->addColumn(['data' => 'monitor_id', 'name' => 'monitor_id', 'title' => trans('alarm.monitor_id')])
            ->addColumn(['data' => 'start_time', 'name' => 'start_time', 'title' => trans('alarm.start_time')])
            ->addColumn(['data' => 'alarm_type', 'name' => 'start_time', 'title' => trans('alarm.start_time')])
            ->addColumn(['data' => 'user_id', 'name' => 'user_id', 'title' => trans('alarm.user_id')])
            ->addColumn(['data' => 'status', 'name' => 'status', 'title' => trans('alarm.status')])
            ->addColumn(['data' => 'mobile_phone', 'name' => 'mobile_phone', 'title' => trans('alarm.mobile_phone')])
            ->addColumn(['data' => 'confirm_time', 'name' => 'confirm_time', 'title' => trans('alarm.confirm_time')])
            ->addAction(['data' => 'action', 'name' => '', 'title' => trans('alarm.action')]);

            return compact('html');
        }

    /**
     * datatable数据
     * @return mixed
     */
    public function ajaxData() {
    	return Datatables::of(Monitor_alarmRepositoryEloquent::all())
			->addIndexColumn()
			->addColumn('action', function ($permission)
			{
				return $this->getActionButtonAttribute($permission->id);
			})
			->make(true);
    }

    /**
     * 实时监测json数据
     * @return json
     */
    public function ajaxJsonData() {

        // 报警响应实时信息记录
        $info = [];
        $all_alarm_info = Monitor_alarmRepositoryEloquent::all();
        foreach ($all_alarm_info as $key => $value) {
            $all_alarm_info_array[$key]['start_time'] = $all_alarm_info[$key]['start_time'];
            $all_alarm_info_array[$key]['status'] = $all_alarm_info[$key]['status'];
            $all_alarm_info_array[$key]['monitor_id'] = $all_alarm_info[$key]['monitor_id'];
            $temp_loop_name = $this->monitor->where('monitor_id',$all_alarm_info_array[$key]['monitor_id'])->first();
            $all_alarm_info_array[$key]['loop_name'] = $temp_loop_name['loop_name'];
            $all_alarm_info_array[$key]['mobile_phone'] = $all_alarm_info[$key]['mobile_phone'];
            $all_alarm_info_array[$key]['cable_temp'] = $all_alarm_info[$key]['cable_temp'];
            $all_alarm_info_array[$key]['fire'] = $all_alarm_info[$key]['fire'];
            $all_alarm_info_array[$key]['smoke'] = $all_alarm_info[$key]['smoke'];
            $all_alarm_info_array[$key]['near_infrared'] = $all_alarm_info[$key]['near_infrared'];
        }
        return [

            "data" => $all_alarm_info_array
            ];
            //Monitor_alarmRepositoryEloquent::all();
    }

    /**
     * 重写datatable action按钮
     * @param $id
     * @return string
     */
    public function getActionButtonAttribute($id)
    {
        return $this->getShowActionButtion($id).
            $this->getEditActionButton($id).
            $this->getDestroyActionButton($id);
    }

    /**
     * 查看
     * @param $id
     * @return array|\Illuminate\Http\RedirectResponse
     */
    public function show($id)
    {
        // try {
        //     $user = UserRepositoryEloquent::with(['userPermissions', 'roles'])->find(decodeId($id, $this->module));
        //     $permissions = $this->getAllPermissions();
        //     $roles = $this->getAllRole();
        //     return compact('user', 'permissions', 'roles');
        // } catch (Exception $e) {
        //     flash(trans('common.find_error'), 'danger');
        //     return redirect()->route($this->indexRoute);
        // }
    }

    // ajax处理警报消除功能
    // 注：目前只能单个测点测试
    public function ajaxAlarmCancel() {
        // 取出当前报警点
        $now_alarm_item = $this->monitor_alarm->where('status',0)->first();
        // dump($now_alarm_item);die;
        // 暂存当时的测点各个属性信息
        $now_monitor_id = $now_alarm_item['monitor_id'];
        $now_alarm_start_time = $now_alarm_item['start_time'];
        $now_alarm_temp = $now_alarm_item['cable_temp'];
        $now_alarm_fire = $now_alarm_item['fire'];
        $now_alarm_smoke = $now_alarm_item['smoke'];
        $now_alarm_near_infrared = $now_alarm_item['near_infrared'];
        // dump($now_monitor_id);die;
        // 取出当前的实时监测信息
        $now_core_info = $this->coring->where('core_id',$now_monitor_id)->first();
        // dump($now_core_info);die;
        // 取出四项检测指标信息
        $now_core_temp = $now_core_info['cable_temp'];
        // dump($now_core_temp);die;
        $now_core_fire = $now_core_info['fire'];
        $now_core_smoke = $now_core_info['smoke'];
        $now_core_near_infrared = $now_core_info['near_infrared'];
        // 从monitor表中取出当前monitor_id的温度额定值
        $now_core_temp_normal = $this->monitor->where('monitor_id',$now_monitor_id)->pluck('cable_temp')->toArray();
        // dump($now_core_temp_normal);die;
        // 存储温度比对值$res1
        $res1 = $now_core_temp < $now_core_temp_normal[0];
        // dump($res1);die;
        // 判断是否恢复正常值
        if ($res1 && !$now_core_fire && !$now_core_smoke && !$now_core_near_infrared ) {
            // 存储消除警报操作时间
            $end_time = date('Y-m-d H:i:s',time());
            // 更新monitor表
            $res2 = DB::table('monitor_alarm')->where('monitor_id',$now_monitor_id)->update(['status' => 3,'mobile_phone' => 0,'cable_temp' => 0,'smoke' => 0,'fire' => 0,'near_infrared' => 0]);
            // dump($res2);die;
            // 向报警历史表插入记录
            // 已知开始时间、结束时间
            $deal_user = auth()->user()->username;
            if ($res1) $now_alarm_temp = 0;
            else $now_alarm_temp = 1;
             $res3 = DB::table('monitor_alarm_history')->insert(['start_time' => $now_alarm_start_time,'cable_temp' => $now_alarm_temp,'fire' => $now_alarm_fire,'smoke' => $now_alarm_smoke,'near_infrared' => $now_alarm_near_infrared,'status' => 3,'user_id' => $deal_user,'monitor_id' => $now_monitor_id,
                'confirm_time' => $end_time]);
            if ($res2) {
                return response()->json(array(
                        'res' => 1
                    ));
            } else {
                return response()->json(array(
                        'res' => 0
                    ));
            }
        } else {
            return response()->json(array(
                    'res' => 0
                ));
        }




    }
}